package org.fall.srb.core.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import lombok.extern.slf4j.Slf4j;
import org.fall.srb.core.mapper.DictMapper;
import org.fall.srb.core.pojo.dto.ExcelDictDTO;

import java.util.ArrayList;
import java.util.List;

/**
 * @author sprogFall
 * @since 2021/7/13 22:42
 */
@Slf4j
public class ExcelDictDtoListener extends AnalysisEventListener<ExcelDictDTO> {

    private final DictMapper dictMapper;

    List<ExcelDictDTO> list = new ArrayList<>();
    private static final Integer MAX_LIST_LENGTH = 5;


    public ExcelDictDtoListener(DictMapper dictMapper) {
        this.dictMapper = dictMapper;
    }

    @Override
    public void invoke(ExcelDictDTO data, AnalysisContext analysisContext) {
        log.info("解析到一条记录：{}", data);
        // 进行插入操作
        list.add(data);
        if (list.size() >= MAX_LIST_LENGTH) {
            dictMapper.batchSave(list);
            list.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        if (list.size() > 0) {
            log.info("剩余{}条数据，开始存储", list.size());
            dictMapper.batchSave(list);
            list.clear();
        }
        log.info("所有记录解析完成！");
    }
}
